package com.tuling.netty.server.handler;

import com.tuling.netty.command.Cmd;
import com.tuling.netty.command.CmdHandler;
import com.tuling.netty.command.CmdHandlerMapping;
import com.tuling.netty.session.Session;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class NettyServerHandler extends SimpleChannelInboundHandler<Cmd> {

    // 服务端读空闲次数
    private int readIdleTimes;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Cmd cmd) throws Exception {
        // 使用命令模式, 针对不同的命令使用不同的处理器进行处理
        CmdHandlerMapping handlerMapping = new CmdHandlerMapping();
        CmdHandler handler = handlerMapping.getHandler(cmd);
        handler.handle(ctx, cmd);
        readIdleTimes = 0;
    }

    /**
     * 当有客户端连接时处罚的方法
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        log.info("客户端:{}上线", channel.remoteAddress());
    }

    /**
     * 服务端每5秒如果产生读空闲, 那么就会触发一次该方法.
     * 对读空闲次数累加, 大于等于5次 kill客户端.
     *
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent event = (IdleStateEvent) evt;
        IdleState state = event.state();

        switch (state) {
            case READER_IDLE:
                readIdleTimes++;
                break;
            default:
                super.userEventTriggered(ctx, evt);
        }

        closeChannelIfNecessary(ctx);
    }

    /**
     * 处理客户端心跳, 当服务端连续5次，每次间隔5秒钟 未收到客户端发送的心跳信息,那么直接kill
     *
     * @param ctx
     * @throws InterruptedException
     */
    private void closeChannelIfNecessary(ChannelHandlerContext ctx) throws InterruptedException {
        // 连续5次没有收到客户端心跳
        if (readIdleTimes >= 5) {
            log.warn("服务端连续5次未收到客户端心跳信息, 倒计时3秒后关闭连接...");

            Channel channel = ctx.channel();

            for (int i = 0; i < 3; i++) {
                log.info("----->{}<-----", (3 - i));
                TimeUnit.SECONDS.sleep(1);
            }
            Session.getSession().unbind(channel);
            channel.close();
        }
    }

    /**
     * 客户端下线触发的方法.
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        log.info("客户端:{}下线", channel.remoteAddress());
        Session.getSession().unbind(channel);
    }


}
